<template>
  <div class="app-container">
    <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" >
        <div style="display: inline-block;width: 300px;">
          <el-form-item label="采购类型" prop="type">
            <el-select v-model="tempPurchaseType" @change="handlePurchaseTypeChange">
              <el-option :value="0" label="成品采购">成品采购</el-option>
              <el-option :value="1" label="物料采购">物料采购</el-option>
            </el-select>
          </el-form-item>
        </div>

        <div style="display: inline-block;width: 300px;">
          <el-form-item label="供应商" prop="customerName">
            <el-select v-model="form.supplierId" @keyup.enter.native="handleQuery" @change="updateFormScId" clearable>
              <el-option v-for="supplier in SupplierList" :key="supplier.id" :value="supplier.id" :label="supplier.name">{{supplier.name}}</el-option>
            </el-select>
          </el-form-item>
        </div>

        <div style="display: inline-block;width: 300px;">
          <el-form-item label="仓库" prop="scName">
            <el-select v-model="form.scId" placeholder="全部" clearable @change="purchaseTypeInfo" :style="{width: '100%'}">
              <el-option v-for="(item, index) in centerList" :key="index" :label="item.name"
                         :value="item.id" >{{item.name}}</el-option>
            </el-select>
          </el-form-item>
        </div>

<!--        <div style="display: inline-block;width: 300px;">-->
<!--          <el-form-item label="采购员" prop="purchaserId" >-->
<!--            <el-select v-model="form.purchaserId" @keyup.enter.native="handleQuery" clearable>-->
<!--              <el-option v-for="user in UserList" :key="user.id" :value="user.id" :label="user.name">{{user.name}}</el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </div>-->
        <div style="display: inline-block;width: 300px;">
          <el-form-item label="预计到货日期" prop="expectArriveDate">
            <el-date-picker clearable
                            v-model="form.expectArriveDate"
                            type="date"
                            style="width: 150px"
                            @input="validateArrivalDate"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择审核时间">
            </el-date-picker>
          </el-form-item>
        </div>
        <div style="display: inline-block;width: 300px;" v-if="this.$route.query.id!=null"><p>状态：<span :style="{color: statusColor}">{{ this.form.status==0 ? '待审核' : (this.form.status==3 ? '审核通过' : '审核拒绝') }}</span></p></div>
        <div style="display: inline-block;width: 300px;" v-if="form.status==6"><p>拒绝原因：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 180px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" v-model="form.refuseReason" disabled></p></div>
        <br>
        <div style="display: inline-block;width: 300px;" v-if="this.$route.query.id!=null"><p>操作人：{{ this.form.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.$route.query.id!=null"><p>操作时间：{{ this.form.createTime }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;" v-if="this.$route.query.id!=null"><p>审核人：{{ this.form.approveBy }}</p></div>
        <div style="display: inline-block;width: 300px;" v-if="this.$route.query.id!=null"><p>审核时间：{{ this.form.approveTime }}</p></div>
      </el-form>
    </div>
    <div>
      <el-row :gutter="10" class="mb8" style="margin: 10px 0">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="medium"
            @click="productAdd"
            v-hasPermi="['system:product:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="medium"
            :disabled="multiple"
            @click="handleDelete('detail')"
            v-hasPermi="['system:product:remove']"
          >删除</el-button>
        </el-col>
        <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
      </el-row>
    </div>
    <div style="border: 1px gainsboro solid;margin-top: 5px">
      <el-table height="400px" v-loading="loading" :data="this.tblPurchaseOrderDetailList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />

<!--        商品数据-->
        <el-table-column label="商品编号" align="left" prop="baseDataProduct.code" width="200px" v-if="purchaseType===0">
          <template slot-scope="scope">
            <span>{{ scope.row.baseDataProduct.code }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="200px" v-if="purchaseType===0">
          <template slot-scope="scope">
            <el-autocomplete
              class="inline-input"
              v-model="scope.row.baseDataProduct.name"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              @select="handleSelect(scope.row,$event)"
            >
              <template slot-scope="{ item }">
                <span>{{ item.name }}</span>
              </template>
            </el-autocomplete>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px" v-if="purchaseType===0"/>
        <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px" v-if="purchaseType===0"/>
        <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px" v-if="purchaseType===0"/>
        <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px" v-if="purchaseType===0"/>

        <!--        物料数据-->
        <el-table-column label="物料编号" align="left" prop="material.materialCode" width="200px" v-if="purchaseType===1">
          <template slot-scope="scope">
            <span>{{ scope.row.material.materialCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="物料名称" align="left" prop="material.materialName" width="200px" v-if="purchaseType===1">
          <template slot-scope="scope">
            <el-autocomplete
              class="inline-input"
              v-model="scope.row.material.materialName"
              :fetch-suggestions="materialQuerySearch"
              placeholder="请输入内容"
              @select="materialHandleSelect(scope.row,$event)"
            >
              <template slot-scope="{ item }">
                <span>{{ item.materialName }}</span>
              </template>
            </el-autocomplete>
          </template>
        </el-table-column>
        <el-table-column label="物料类型" align="left" prop="material.typeName" width="100px" v-if="purchaseType===1"/>
        <el-table-column label="规格型号" align="left" prop="material.specification" width="150px" v-if="purchaseType===1"/>
        <el-table-column label="分类名称" align="left" prop="material.categoryName" width="100px" v-if="purchaseType===1"/>
        <el-table-column label="单位" align="left" prop="material.purchaseUnitName" width="100px" v-if="purchaseType===1"/>

        <el-table-column label="采购价（元）" align="left" prop="taxPrice" width="130px">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.taxPrice" @input="getSumNumber"/>
          </template>
        </el-table-column>
        <el-table-column label="税率（%）" align="left" prop="baseDataProduct.baseDataProductCategory.taxRate" width="100px" v-if="purchaseType===0"/>
        <el-table-column label="采购数量" align="left" prop="orderNum" width="150">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.orderNum" @input="getSumNumber"/>
          </template>
        </el-table-column>
        <el-table-column label="采购含税金额" align="left" prop="" width="100">
          <template slot-scope="scope">
            <span>{{Number(scope.row.taxPrice*scope.row.orderNum).toLocaleString('en-US') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left" prop="description" width="200">
          <template slot-scope="scope">
            <input type="text" v-model="scope.row.description" style="padding: 10px;border-radius: 5px;border: 1px gainsboro solid;width: 180px;">
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
      <h3 style="margin:0 0 15px 10px;font-weight: bolder;">合计</h3>
      <div style="display: inline-block;margin-left:50px">
        采购数量：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled v-model="this.orderNum">
<!--        采购数量：<span>{{this.orderNum}}</span>-->
      </div>
      <div style="display: inline-block;margin-left:50px">
<!--        含税总金额：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled v-model="this.taxAmount">-->
        含税总金额：<span>{{Number(this.taxAmount).toLocaleString('en-US')}}</span>
      </div>
    </div>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
      <h3 style="margin:0 0 15px 10px;font-weight: bolder;margin-left: 10px">约定支付</h3>
      <el-row :gutter="10" class="mb8" style="margin-left: 20px">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="payTypeAdd"
            v-hasPermi="['system:product:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete('pay')"
            v-hasPermi="['system:product:remove']"
          >删除</el-button>
        </el-col>
      </el-row>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
        <el-table :data="OrderPayTypeList" height="300px" ref="tblPurchaseOrderDetail" @selection-change="handlePaySelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="支付方式" prop="payTypeId" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.payTypeId" @change="orderPayTypeInfo(scope.row)" clearable>
                <el-option v-for="(type,index) in PayTypeList" :key="index" :value="type.id" :label="type.name">{{type.name}}</el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="支付金额" prop="payAmount" width="300">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.payAmount" placeholder="请输入支付金额"/>
            </template>
          </el-table-column>
          <el-table-column label="支付记录" prop="text" width="650">
            <template slot-scope="scope">
              <el-input v-model="scope.row.text" placeholder="请输入支付记录" style="width: 300px"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px;text-align: right">
      <label >备注： </label>
      <textarea v-model="form.description" style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid"/>
    </div>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm(0)">确 定</el-button>
<!--      <el-button type="success" @click="submitForm(3)" v-if="this.$route.query.id==null">审批通过</el-button>-->
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {parseTime} from "../../../utils/ruoyi";
import {
  getPurchaseOrder,
  addPurchaseOrder,
  updatePurchaseOrder,
  listPurchaseOrder,
  delPurchaseOrder
} from "@/api/system/PurchaseOrder";
import {listUser} from "@/api/system/user";
import {listSupplier} from "@/api/system/Supplier";
import {listStoreCenterInfo} from "@/api/system/StoreCenterInfo";
import {listTblOrderPayType}from "@/api/system/TblOrderPayType"
import {listPayType}from "@/api/system/PayType";
import {listProductInfo} from "@/api/system/ProductInfo";
import {listProductCategory} from "@/api/system/ProductCategory";
import {listMaterial} from "@/api/system/Material";
import {listCategory} from "@/api/system/Category";

export default {
  name: "orderAdd",
  data() {
    return {
      //采购类型
      purchaseType:null,
      tempPurchaseType:null,
      originalPurchaseType:0,
      materialList:[],
      typeInfo:false,

      //供应商下拉框
      supplierOption:"",

      // 遮罩层
      loading: true,
      // 商品选中数组
      ids: [],
      // 支付方式选中数组
      payIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 商品数据
      productList: [],
      // 销售数量
      orderNum: 0,
      // 赠品数量
      giftNum: 0,
      // 含税总金额
      taxAmount: 0,

      //状态颜色
      statusColor:"rgb(100, 100, 100)",
      //用户列表
      UserList: [],
      //支付方式
      OrderPayTypeList: [],
      // 供应商列表
      SupplierList: [],
      //仓库数据列表
      StoreCenterInfoList: [],
      //仓库下拉框数据
      centerList: [],

      // 采购订单明细表格数据
      tblPurchaseOrderDetailList: [],
      // 采购订单表格数据
      PurchaseOrderList: [],
      // 支付下拉框
      PayTypeList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scName: null,
        customerName: null,
      },
      // 订单支付参数
      orderPayTypeParams:{
        orderId: null
      },
      // 支付参数
      payTypeParams:{
      },
      // 表单参数
      form: {
        id:null,
        code:null,
        scId:null,
        scCode:null,
        scName:null,
        supplierId:null,
        supplierCode:null,
        supplierName:null,
        purchaserId:null,
        purchaseName:null,
        expectArriveDate:null,
        totalNum:0,
        totalGiftNum:0,
        totalAmount:0,
        description:"",
        createBy:null,
        createById:null,
        createTime:null,
        updateBy:null,
        updateById:null,
        updateTime:null,
        approveBy:null,
        approveTime:null,
        status:null,
        refuseReason:null,
        remark:null,
        tblOrderPayTypeList:[],
        tblPurchaseOrderDetailList:[]
      },
      // 根据订单ID查询订单支付方式
      payType: {
        orderId: null,
      },
      // 表单校验
       rules: {
        code: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
      },

      //商品数据框
      restaurants: [],
      //物料数据框
      materialRestaurants: [],
      state1: '',
      state2: '',
      // 查询参数
      productQueryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        shortName: null,
        skuCode: null,
        categoryId: null,
        brandId: null,
        productType: null,
        available: null,
        createTime: null,
      },
      //订单表ID数据
      OrderAllList:[],
      //订单详情表ID数据
      OrderDetailAllList:[],
      //订单支付ID数据
      orderPayTypeAllList:[],


    };
  },
  created() {
    //用户数据
    this.getUserList();
    //供应商数据
    this.getSupplierList();
    //仓库数据
    this.getStoreCenterInfoList();
    //支付方式
    this.getPayType();
    //商品数据
    this.getProductList();
    //物料数据
    this.getMaterialList();
    //订单数据
    this.getList()
    //订单详情数据
    this.getPurchaseOrderAllList();
    if (this.$route.query.id!=null){
      this.selectOrder();
    }

    this.loading = false;
  },
  methods: {
    parseTime,
    /** 查询采购订单列表 */
    getList() {
      this.OrderAllList=[];
      var list=[];

      listPurchaseOrder({}).then(response => {
        this.PurchaseOrderList = response.rows;

        list=response.rows;
        for (var i=0;i<list.length;i++){
          this.OrderAllList.push(list[i].id);
        }
      });
    },
    /** 查询订单详情 */
    selectOrder() {
      const id = this.$route.query.id
      getPurchaseOrder(id).then(response => {
        // 订单赋值
        this.form = response.data;

        //供应商
        this.supplierOption=response.data.supplierId;

        //类型
        this.purchaseType=response.data.tblPurchaseOrderDetailList[0].purchaseType;
        this.tempPurchaseType=response.data.tblPurchaseOrderDetailList[0].purchaseType;

        //订单详情
        this.tblPurchaseOrderDetailList = response.data.tblPurchaseOrderDetailList;
        if (this.purchaseType==1){
          for (let i = 0; i < this.tblPurchaseOrderDetailList.length; i++) {
            let num=this.tblPurchaseOrderDetailList[i].material.materialType
            let name= num===1 ? "原材料" : num===2 ? "半成品" :num===3 ? "成品" : "辅料"
            this.tblPurchaseOrderDetailList[i].material.typeName=name
          }
        }

        //仓库列表
        for (let i = 0; i < this.StoreCenterInfoList.length; i++) {
          if (this.StoreCenterInfoList[i].categoryType==1 && this.purchaseType===0){
            this.centerList.push(this.StoreCenterInfoList[i]);
          }else if (this.StoreCenterInfoList[i].categoryType==2 && this.purchaseType===1){
            this.centerList.push(this.StoreCenterInfoList[i]);
          }
        }

        //商品列表
        if (this.purchaseType===0){
          this.updateProduct();
        }else {
          this.updateMaterial();
        }

        //支付方式
        this.OrderPayTypeList=response.data.tblOrderPayTypeList;
        // this.getOrderPayType(this.form.id);

        this.loading = false;

        //状态值颜色判断
        if (response.data.status == 0){
          this.statusColor = "rgb(100, 100, 100)";
        }else if (response.data.status==3){
          this.statusColor = "rgb(82, 196, 26)";
        }else {
          this.statusColor = "rgb(255, 0, 0)";
        }

        this.getSumNumber();
      });
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.UserList = response.rows;
      });
    },
    /** 查询供应商列表 */
    getSupplierList() {
      this.loading = true;
      listSupplier(this.queryParams).then(response => {
        this.SupplierList = response.rows;
      });
    },
    /** 查询仓库列表 */
    getStoreCenterInfoList() {
      this.loading = true;
      listStoreCenterInfo(this.queryParams).then(response => {
        this.StoreCenterInfoList = response.rows;
      });
    },
    /** 查询支付方式 */
    getPayType() {
      listPayType(this.payTypeParams).then(response => {
        this.PayTypeList = response.rows;
      });
    },
    /** 查询订单支付方式 */
    // getOrderPayType(id) {
    //   this.orderPayTypeParams.orderId = id;
    //   listTblOrderPayType(this.orderPayTypeParams).then(response => {
    //     this.OrderPayTypeList = response.rows;
    //   });
    // },

    getSumNumber(){
      const list=this.tblPurchaseOrderDetailList;

      this.orderNum=0;
      this.taxAmount=0;
      this.giftNum=0;

      for (var i=0;i<list.length;i++){
        this.orderNum+=Number(list[i].orderNum);
        this.taxAmount+=list[i].taxPrice*list[i].orderNum;
      }

      this.form.totalAmount=this.taxAmount;
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 支付方式多选框选中数据
    handlePaySelectionChange(selection) {
      this.payIds = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
    },
    /** 提交按钮 */
    submitForm(status) {
      if(this.formInfo()){
        if (this.form.id != null) {
          this.form.totalNum=this.orderNum
          this.form.tblPurchaseOrderDetailList=this.tblPurchaseOrderDetailList
          this.form.tblOrderPayTypeList=this.OrderPayTypeList
          updatePurchaseOrder(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        } else {
          const newId = generateUniqueId(this.OrderAllList);
          var orderCode = getOrderCode(this.PurchaseOrderList);
          this.form.id=newId;
          this.form.code=orderCode;
          for (var i = 0; i < this.tblPurchaseOrderDetailList.length; i++) {
            this.tblPurchaseOrderDetailList[i].returnNum=0;
            this.tblPurchaseOrderDetailList[i].orderId=newId;
            this.tblPurchaseOrderDetailList[i].purchaseType=this.purchaseType;
          }
          for (var i = 0; i < this.OrderPayTypeList.length; i++) {
            this.OrderPayTypeList[i].orderId=newId;
          }
          this.form.tblOrderPayTypeList=this.OrderPayTypeList;
          this.form.tblPurchaseOrderDetailList=this.tblPurchaseOrderDetailList;
          this.form.totalNum=this.orderNum;
          this.form.totalGiftNum=this.giftNum;
          this.form.totalAmount=this.taxAmount;
          this.form.status=status;
          if (status==3){
            this.form.approveBy="系统管理员";
            this.form.approveTime=new Date();
          }

          addPurchaseOrder(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        }
      }
    },
    //提交表单验证
    formInfo(){
      if (this.form.scId==null){
        this.$modal.msgError("请选择仓库");
        return false;
      }else if (this.form.supplierId==null){
        this.$modal.msgError("请选择供应商");
        return false;
      }else if (this.form.expectArriveDate==null){
        this.$modal.msgError("请选择预计到货日期");
        return  false;
      }

      //订单详情验证
      if (this.tblPurchaseOrderDetailList.length<=0){
        this.$modal.msgError("请添加采购货物");
        return false;
      }
      for (var i=0;i<this.tblPurchaseOrderDetailList.length;i++){
        if (this.purchaseType==0){
          if (this.tblPurchaseOrderDetailList[i].productId==null || this.tblPurchaseOrderDetailList[i].productId==""){
            this.$modal.msgError("商品名称不能为空");
            return false;
          }
        }else {
          if (this.tblPurchaseOrderDetailList[i].materialId==null || this.tblPurchaseOrderDetailList[i].materialId==""){
            this.$modal.msgError("物料名称不能为空");
            return false;
          }
        }

        if (this.tblPurchaseOrderDetailList[i].orderNum==null || this.tblPurchaseOrderDetailList[i].orderNum===0){
          this.$modal.msgError("采购数量不能为空或0");
          return false;
        }else if (this.tblPurchaseOrderDetailList[i].taxPrice==null || this.tblPurchaseOrderDetailList[i].taxPrice===0){
          this.$modal.msgError("采购单价不能为空或0");
          return false;
        }
      }

      //支付方式验证
      var sum=0;
      for (var j=0;j<this.OrderPayTypeList.length;j++){
        sum+=Number(this.OrderPayTypeList[j].payAmount);
        if (this.OrderPayTypeList[j].payTypeId==null){
          this.$modal.msgError("请选择支付方式");
          return false;
        }else if (this.OrderPayTypeList[j].payAmount==null){
          this.$modal.msgError("请输入支付金额");
          return false;
        }
      }

      if(sum!=this.form.totalAmount){
        this.$modal.msgError("支付金额与订单金额不相等");
        return false;
      }
      return true;
    },
    /** 删除按钮操作 */
    handleDelete(name) {
      if(name=="detail") {
        if (this.ids.length === 0) {
          this.$message.warning('请选择要删除的行');
          return;
        }
        this.tblPurchaseOrderDetailList = this.tblPurchaseOrderDetailList.filter(item => !this.ids.includes(item.id));
        this.ids = [];
        this.getSumNumber(); // 重新计算合计
      }else {
        if (this.payIds.length === 0) {
          this.$message.warning('请选择要删除的行');
          return;
        }
        this.OrderPayTypeList = this.OrderPayTypeList.filter(item => !this.payIds.includes(item.id));
        this.payIds = [];
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/SettleInItem/export', {
        ...this.queryParams
      }, `SettleInItem_${new Date().getTime()}.xlsx`)
    },

    // 商品框
    querySearch(queryString, cb) {
      var restaurants = this.productList;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

    // 物料框
    materialQuerySearch(queryString, cb) {
      var restaurants = this.materialList;
      var results = queryString ? restaurants.filter(this.materialCreateFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    materialCreateFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

    getProductList() {
      listProductInfo({}).then(response => {
        this.restaurants = response.rows.map(item => ({
          value: item.id,  // 使用商品 ID 作为 value
          name: item.name,
          code: item.code,
          skuCode: item.skuCode,
          externalCode: item.externalCode,
          unit: item.unit,
          spec: item.spec,
          categoryId:item.categoryId,
          baseDataProductCategory: item.baseDataProductCategory,
          baseDataProductBrand: item.baseDataProductBrand,
          baseDataProductPurchase: item.baseDataProductPurchase
        }));
      });
    },
    getMaterialList() {
      listMaterial({}).then(response => {
        this.materialRestaurants = response.rows.map(item => ({
          value: item.id,  // 使用物料 ID 作为 value
          materialName: item.materialName,
          materialCode: item.materialCode,
          materialType: item.materialType,

          typeName: item.materialType==1 ? "原材料" : item.materialType==2 ? "半成品" : item.materialType==3 ? "成品" : "辅料",

          specification:item.specification,
          categoryId: item.categoryId,
          categoryName: item.categoryName,
          purchaseUnitName: item.purchaseUnitName,
          storageUnitName:  item.storageUnitName,
          standardPrice:  item.standardPrice,
        }));
      });
    },

    handleSelect(row, item) {
      // 将选中的商品名称赋值给当前行的商品名称
      row.baseDataProduct.name = item.name;
      // 将选中的商品 ID 赋值给当前行的商品 ID
      row.baseDataProduct.id = item.value;
      row.productId=item.value;
      // 将选中的商品 Code 编号赋值给当前行的商品 Code 编号
      row.baseDataProduct.code = item.code;
      // 将选中的商品 SKU 编号赋值给当前行的商品 SKU 编号
      row.baseDataProduct.skuCode = item.skuCode;
      // 将选中的商品外部编号赋值给当前行的商品外部编号
      row.baseDataProduct.externalCode = item.externalCode;
      // 将选中的商品单位赋值给当前行的商品单位
      row.baseDataProduct.unit = item.unit;
      // 将选中的商品规格赋值给当前行的商品规格
      row.baseDataProduct.spec = item.spec;
      // 将选中的商品类目赋值给当前行的商品类目
      row.baseDataProduct.baseDataProductCategory = item.baseDataProductCategory;
      // 将选中的商品品牌赋值给当前行的商品品牌
      row.baseDataProduct.baseDataProductBrand = item.baseDataProductBrand;
      // 将选中的商品采购价赋值给当前行的商品采购价
      row.taxPrice = item.baseDataProductPurchase.price;

      let count = 0;
      for (let i = 0; i <this.tblPurchaseOrderDetailList.length ; i++) {
        if (this.tblPurchaseOrderDetailList[i].baseDataProduct.id==item.value){
          count++;
        }
      }
      if (count>1){
        this.$modal.msgError("该商品已存在");
        for (let i = 0; i < this.tblPurchaseOrderDetailList.length; i++) {
          if (this.tblPurchaseOrderDetailList[i].id==row.id){
            this.tblPurchaseOrderDetailList[i].baseDataProduct={};
            this.tblPurchaseOrderDetailList[i].taxPrice=null;
          }
        }
      }
    },

    materialHandleSelect(row, item) {
      row.material.materialName = item.materialName;
      row.material.id = item.value;
      row.materialId=item.value;
      row.material.materialCode = item.materialCode;
      row.material.materialType = item.materialType;
      row.material.typeName = item.typeName;
      row.material.specification = item.specification;
      row.material.categoryName = item.categoryName;
      row.material.purchaseUnitName = item.purchaseUnitName;
      row.material.storageUnitName = item.storageUnitName;
      row.material.standardPrice = item.standardPrice;
      row.taxPrice = item.standardPrice;

      let count = 0;
      for (let i = 0; i <this.tblPurchaseOrderDetailList.length ; i++) {
        if (this.tblPurchaseOrderDetailList[i].material.id==item.value){
          count++;
        }
      }
      if (count>1){
        this.$modal.msgError("该物料已存在");
        for (let i = 0; i < this.tblPurchaseOrderDetailList.length; i++) {
          if (this.tblPurchaseOrderDetailList[i].id==row.id){
            this.tblPurchaseOrderDetailList[i].material={};
            this.tblPurchaseOrderDetailList[i].taxPrice=null;
          }
        }
      }
    },

    //数据添加
    productAdd(){
      if(this.form.supplierId==null || this.form.supplierId==""){
        this.$modal.msgError("请选择供应商");
        return
      }

      const newId = generateUniqueId(this.OrderDetailAllList);
      this.OrderDetailAllList.push(newId);
      if (this.purchaseType===0){
        this.tblPurchaseOrderDetailList.push({
          baseDataProduct: {
            name: '',
          },
          id: newId,
          orderId: this.$route.query.id,
          productId: null,
          orderNum: null,
          taxPrice: null,
          isGift: 0,
          taxRate: 10,
          description: null,
          orderNo: this.tblPurchaseOrderDetailList.length,
          receiveNum: 0,
          returnNum: 0,
          purchaseType:0
        })
      }else {
        this.tblPurchaseOrderDetailList.push({
          material: {
          },
          id: newId,
          orderId: this.$route.query.id,
          materialId: null,
          orderNum: null,
          taxPrice: null,
          isGift: 0,
          taxRate: 10,
          description: null,
          orderNo: this.tblPurchaseOrderDetailList.length,
          receiveNum: 0,
          returnNum: 0,
          purchaseType:1
        })
      }

    },

    //商品数据修改
    updateProduct(){
      this.productList=[];
      listProductCategory({supplierId:this.form.supplierId}).then(response => {
        let list =response.rows

        for (let i = 0; i < list.length; i++) {
          for (let j = 0; j < this.restaurants.length; j++) {
            if (list[i].id==this.restaurants[j].categoryId){
              this.restaurants[j].baseDataProductCategory = list[i];
              this.productList.push(this.restaurants[j])
            }
          }
        }
      });
    },

    //物料数据修改
    updateMaterial(){
      this.materialList=[];
      listCategory({supplierId:this.form.supplierId}).then(response => {
        let list =response.rows

        for (let i = 0; i < list.length; i++) {
          for (let j = 0; j < this.materialRestaurants.length; j++) {
            if (list[i].id==this.materialRestaurants[j].categoryId){
              this.materialRestaurants[j].category = list[i];
              this.materialList.push(this.materialRestaurants[j])
            }
          }
        }
      });

    },

    handlePurchaseTypeChange(value) {
      if (this.tblPurchaseOrderDetailList.length > 0) {
        this.$confirm('修改采购类型将清空采购数据列表，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户点击“确定”，更新真实值
          this.purchaseType = value;
          this.originalPurchaseType = value;

          //仓库下拉数据修改
          this.form.scId=null
          this.centerList=[];
          for (let i = 0; i < this.StoreCenterInfoList.length; i++) {
            if (this.StoreCenterInfoList[i].categoryType==1 && this.purchaseType===0){
              this.centerList.push(this.StoreCenterInfoList[i]);
            }else if (this.StoreCenterInfoList[i].categoryType==2 && this.purchaseType===1){
              this.centerList.push(this.StoreCenterInfoList[i]);
            }
          }

          this.updatePurchaseType(); // 执行原来 updatePurchaseType 方法里的逻辑
        }).catch(() => {
          // 用户点击“取消”，恢复临时值为原始值
          this.tempPurchaseType = this.originalPurchaseType;
        });
      } else {
        // 没有数据，直接更新
        this.purchaseType = value;
        this.originalPurchaseType = value;
        this.tempPurchaseType = value;
      }

      //仓库下拉数据修改
      this.form.scId=null
      this.centerList=[];
      for (let i = 0; i < this.StoreCenterInfoList.length; i++) {
        if (this.StoreCenterInfoList[i].categoryType==1 && this.purchaseType===0){
          this.centerList.push(this.StoreCenterInfoList[i]);
        }else if (this.StoreCenterInfoList[i].categoryType==2 && this.purchaseType===1){
          this.centerList.push(this.StoreCenterInfoList[i]);
        }
      }
    },

    updatePurchaseType() {
      // 清空采购明细等逻辑
      this.tblPurchaseOrderDetailList = [];
      this.getSumNumber();
      if (this.purchaseType === 0) {
        this.updateProduct();
      } else {
        this.updateMaterial();
      }
    },

    purchaseTypeInfo(){
      if (this.purchaseType==null){
        this.form.scId=null
        this.$modal.msgError("请先选择采购类型！");
      }
    },

    updateFormScId(){
      if (this.purchaseType==null){
        this.form.supplierId=null
        this.$modal.msgError("请先选择采购类型！");
        return
      }
      if (this.tblPurchaseOrderDetailList.length>0){
        this.$modal.confirm('修改供应商信息将清空采购数据列表，是否继续？').then(()=> {
          this.tblPurchaseOrderDetailList=[];
          this.getSumNumber();
          this.supplierOption=this.form.supplierId
        }).catch(() => {
          this.form.supplierId=this.supplierOption
        });
      }else {
        this.supplierOption=this.form.supplierId
      }
      if (this.purchaseType===0){
        this.updateProduct();
      }else {
        this.updateMaterial();
      }
    },


    //支付方式验证
    orderPayTypeInfo(row){
      let count=0;
      for (let i = 0; i <this.OrderPayTypeList.length ; i++) {
        if (this.OrderPayTypeList[i].payTypeId===row.payTypeId){
          count++;
        }
      }
      if (count>1){
        this.$modal.msgError("该支付方式已存在！");
        for (let i = 0; i <this.OrderPayTypeList.length ; i++) {
          if (this.OrderPayTypeList[i].id===row.id){
            this.OrderPayTypeList[i].payTypeId=null;
          }
        }
      }
    },

    //支付方式添加
    payTypeAdd(){
      const newId = generateUniqueId(this.orderPayTypeAllList);
      this.orderPayTypeAllList.push(newId);
      if (this.OrderPayTypeList.length===0){
        this.OrderPayTypeList.push({
          id:newId,
          orderId:this.$route.query.id,
          payTypeId:null,
          payAmount:this.taxAmount,
          text:null
        })
      }else{
        let sum=this.taxAmount;
        for (let i = 0; i < this.OrderPayTypeList.length; i++) {
          sum-=this.OrderPayTypeList[i].payAmount;
        }
        this.OrderPayTypeList.push({
          id:newId,
          orderId:this.$route.query.id,
          payTypeId:null,
          payAmount:sum,
          text:null
        })
      }
    },
    // 获取所有订单详情数据ID
    getPurchaseOrderAllList(){
      this.OrderDetailAllList=[];
      var list=[];

      listPurchaseOrder(null).then(response => {
          list=response.rows;

          for (var i=0;i<list.length;i++){
            for (var j=0;j<list[i].tblPurchaseOrderDetailList.length;j++){
              this.OrderDetailAllList.push(list[i].tblPurchaseOrderDetailList[j].id);
            }
          }
      });
    },

    resetTime(date) {
      date.setHours(0, 0, 0, 0);
      return date;
    },

      //日期验证
    validateArrivalDate() {
      const today = this.resetTime(new Date()); // 当前日期，时间归零
      const selectedDate = this.resetTime(new Date(this.form.expectArriveDate)); // 输入日期，时间归零

      if (selectedDate < today) {
        this.$modal.msgError("预计到货日期不能小于当天！");
        this.form.expectArriveDate = ''; // 清空非法输入
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    // 设置一个标志，表示需要刷新数据
    to.meta.refresh = true;
    next();
  }
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}

//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="CGDD";    //采购订单
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>

